import React, { useState } from 'react';
import {
  Form,
  Row,
  Col,
  Button,
  DatePicker,
  Select,
  Table,
  Tag,
  Space,
  message,
} from 'antd';
import moment from 'moment';
import { PlusOutlined } from '@ant-design/icons';
import request from '@/http';
const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  const [expand, setExpand] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const formItemLayout = {
    labelCol: {
      xs: { span: 7 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const [select, setSelect] = useState([]);
  const loadSelect = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getTeacher',
    );
    if (result.success) {
      setSelect(result.data);
      setLoading(false);
    }
  };
  React.useEffect(() => {
    loadSelect().then();
  }, []);

  const [select2, setSelect2] = useState([]);
  const loadSelect2 = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getCourse',
    );
    if (result.success) {
      setSelect2(result.data);
      setLoading(false);
    }
  };
  React.useEffect(() => {
    loadSelect2();
  }, []);

  const getFields = () => {
    const count = expand ? 10 : 6;
    const children = [];

    children.push(
      <Col span={8}>
        <Form.Item name="date" label="日期:">
          <RangePicker
            style={{
              width: '100%',
            }}
            ranges={{
              Today: [moment(), moment()],
              'This Month': [
                moment().startOf('month'),
                moment().endOf('month'),
              ],
            }}
          />
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="courseName" label="项目名称">
          <Select
            placeholder="请选择..."
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            filterSort={(optionA, optionB) =>
              optionA.children
                .toLowerCase()
                .localeCompare(optionB.children.toLowerCase())
            }
          >
            {select2.map((item: any) => {
              return <Option value={item.courseName}>{item.courseName}</Option>;
            })}
          </Select>
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="trainTeacher" label="实训老师">
          <Select
            placeholder="请选择..."
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            filterSort={(optionA, optionB) =>
              optionA.children
                .toLowerCase()
                .localeCompare(optionB.children.toLowerCase())
            }
          >
            {select.map((item: any) => {
              return (
                <Option value={item.teacherName}>{item.teacherName}</Option>
              );
            })}
          </Select>
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="dutyTeacher" label="责任老师">
          <Select
            placeholder="请选择..."
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            filterSort={(optionA, optionB) =>
              optionA.children
                .toLowerCase()
                .localeCompare(optionB.children.toLowerCase())
            }
          >
            {select.map((item: any) => {
              return (
                <Option value={item.teacherName}>{item.teacherName}</Option>
              );
            })}
          </Select>
        </Form.Item>
      </Col>,
    );
    return children;
  };

  const columns = [
    {
      title: '日期',
      dataIndex: 'projectDate',
      key: 'projectDate',
    },
    {
      title: '项目名称  ',
      dataIndex: 'courseName',
      key: 'courseName',
    },
    {
      title: '实训老师',
      dataIndex: 'trainTeacher',
      key: 'trainTeacher',
    },
    {
      title: '责任老师',
      dataIndex: 'dutyTeacher',
      key: 'dutyTeacher',
    },
    {
      title: '签到时间',
      dataIndex: 'signInTime',
      key: 'signInTime',
    },
    {
      title: '签退时间',
      dataIndex: 'signOutTime',
      key: 'signOutTime',
    },
    {
      title: '教室',
      dataIndex: 'classRome',
      key: 'classRome',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
  ];

  const [total, setTotal] = useState('');
  const [data, setData] = useState([]);
  const pagination = {
    total: parseInt(total),
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['5', '10', '50', '100'],
  };
  const loadDataSource = async (
    queryParams: any,
    pageNumber: any,
    pageSize: any,
  ) => {
    try {
      setLoading(true);
      const result: any = await request.get(
        '/api/student/course/getAllCourse',
        {
          params: {
            ...queryParams,
            pageNumber: pageNumber,
            pageSize: pageSize,
          },
        },
      );
      let sum = 0;
      if (result.message == '成功!') {
        const data = result.data.records.map((course: any) => ({
          key: `data_${sum++}`,
          id: course.id,
          projectDate: course.projectDate,
          courseName: course.courseName,
          trainTeacher: course.trainTeacher,
          dutyTeacher: course.dutyTeacher,
          signInTime: course.signInTime,
          signOutTime: course.signOutTime,
          classRome: course.classRome,
          remark: course.remark,
        }));
        setLoading(false);
        setData(data);
        setTotal(result.data.total);
      }
    } catch (e) {
      message.error('请求错误');
    }
  };
  React.useEffect(() => {
    loadDataSource('', '', '').finally();
  }, []);

  const onFinish = (values: any) => {
    console.log(values.courseName);
    const data = {
      courseName: values.courseName,
      trainTeacher: values.trainTeacher,
      dutyTeacher: values.dutyTeacher,
      startDate: values.date ? values.date[0].format('yyyy-MM-DD') : '',
      endDate: values.date ? values.date[1].format('yyyy-MM-DD') : '',
    };
    loadDataSource(data, '', '').then();
  };

  const pageOnChange = (page: any) => {
    const data = {
      courseName: form.getFieldsValue().courseName,
      trainTeacher: form.getFieldsValue().trainTeacher,
      dutyTeacher: form.getFieldsValue().dutyTeacher,
      startDate: form.getFieldsValue().date
        ? form.getFieldsValue().date[0].format('yyyy-MM-DD')
        : '',
      endDate: form.getFieldsValue().date
        ? form.getFieldsValue().date[1].format('yyyy-MM-DD')
        : '',
    };
    loadDataSource(data, page.current, page.pageSize).then();
  };

  return (
    <>
      <Form
        {...formItemLayout}
        form={form}
        name="advanced_search"
        className="ant-advanced-search-form"
        onFinish={onFinish}
      >
        <Row gutter={24}>{getFields()}</Row>
        <Row>
          <Col span={24} style={{ textAlign: 'left' }}>
            <Button type="primary" style={{ width: '7%' }} htmlType="submit">
              查询
            </Button>
            <Button
              style={{ margin: '0 8px', width: '7%' }}
              onClick={() => {
                form.resetFields();
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
      <Table
        loading={loading}
        columns={columns}
        pagination={pagination}
        dataSource={data}
        onChange={pageOnChange}
      />
    </>
  );
};
